<template>
    <h2 style="margin-bottom: 12px;">| 员工管理</h2>
    <!-- 新增和批量删除员工 -->
    <el-button type="primary" @click="addEmpDialog">+ 新增员工</el-button>
    <el-button @click="deleteEmps" type="danger">- 批量删除</el-button>
    <!-- 模糊查询选项 -->
    <el-form :inline="true" :model="searchEmp" style="margin: 20px 0 8px 0;">
      <el-form-item label="姓名: ">
        <el-input v-model="searchEmp.name" placeholder="输入员工姓名"/>
      </el-form-item>
      <el-form-item v-model="searchEmp.gender" label="性别：">
        <el-select
          v-model="searchEmp.gender"
          placeholder="性别"
          style="width: 80px;"
        >
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="入职时间：">
        <el-date-picker
          type="daterange"
          v-model="searchEmp.date"
          unlink-panels
          range-separator="到"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query">查询</el-button>
        <el-button @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
    <!-- 员工列表 -->
    <el-table :data="empTableData" border @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" :selectable="selectable" width="55" /> -->
      <el-table-column type="selection" align="center" width="55" />
      <el-table-column prop="name" align="center" label="姓名" />
      <el-table-column prop="gender" align="center" label="性别">
        <template #default="scope" >
          {{ scope.row.gender == 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="deptName" align="center" label="所属部门" />
      <el-table-column prop="entryDate" align="center" label="入职日期" />
      <el-table-column prop="updateTime" align="center" label="最后操作时间" />
      <!-- 新增删除操作 -->
      <el-table-column align="center" label="操作" prop="id">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDel(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页展示 -->
    <el-pagination
      :page-sizes="[10, 20, 50, 100]"
      layout="sizes, total, prev, pager, next, jumper"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 12px;"
    />

    <!-- 新增弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialog_title" width="1000px">
    <el-form :rules="rules" ref="formRef" :model="emp" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="11">
          <el-form-item label="用户名">
            <el-input placeholder="请输入员工用户名，2-20个字" v-model="emp.username"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="姓名">
            <el-input placeholder="请输入员工姓名，2-10个字" v-model="emp.name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="11">
          <el-form-item label="性别">
            <el-select placeholder="请选择" v-model="emp.gender">
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="手机号">
            <el-input placeholder="请输入员工手机号" v-model="emp.phone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="11">
          <el-form-item label="薪资">
            <el-input placeholder="请输入员工薪资" v-model="emp.salary"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="11">
          <el-form-item label="所属部门">
            <el-select placeholder="请选择" v-model="emp.deptId">
              <el-option v-for="item in empsList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="入职日期">
            <el-date-picker
              v-model="emp.entryDate"
              type="date"
              placeholder="请选择入职日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

    

      <el-form-item label="工作经历">
        <div v-for="(work, index) in emp.exprList" :key="index" class="work-experience">
          <el-row :gutter="20">
            <el-col :span="2">
              <div style="line-height: 36px;">时间</div>
            </el-col>
            <el-col :span="4">
              <el-date-picker
                v-model="work.begin"
                type="date"
                placeholder="开始日期"
              ></el-date-picker>
            </el-col>
            <el-col :span="1" style="text-align: center; line-height: 36px;">到</el-col>
            <el-col :span="4">
              <el-date-picker
                v-model="work.end"
                type="date"
                placeholder="结束日期"
              ></el-date-picker>
            </el-col>
            <el-col :span="8">
              <el-input v-model="work.company" placeholder="请输入公司的名字"></el-input>
            </el-col>
            <el-col :span="4">
              <el-input v-model="work.job" placeholder="请输入职位"></el-input>
            </el-col>
            <el-col :span="1">
              <el-button type="text" @click="removeWorkExperience(index)">删除</el-button>
            </el-col>
          </el-row>
        </div>
        <div style="text-align: right; margin-top: 10px;">
          <el-button type="primary" @click="addWorkExperience">添加工作经历</el-button>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { queryShowPageApi, deleteEmpById, addEmpApi, queryByIdApi, updateApi } from '@/api/emp'
import { queryAllapi } from '@/api/dept'
import { onMounted, ref, watch } from 'vue'

import { ElMessage, ElMessageBox } from 'element-plus'

// 条件查询参数
const searchEmp = ref({
  name: '',
  gender: '',
  date: [],
  begin: '',
  end: ''
})
const page = ref(1);
const pageSize = ref(10)
// 表格数据查询结果
const empTableData = ref([]);
// 数据总数 
const total = ref();


onMounted(()=>{
    searchPage()
})

//监听请求数据变化
watch(()=>searchEmp.value.date, ()=>{
  console.log(searchEmp.value.date)
  searchEmp.value.begin = searchEmp.value.date[0]
  searchEmp.value.end = searchEmp.value.date[1]
})

const searchPage = async()=>{
    const res = await queryShowPageApi(searchEmp.value.name,
        searchEmp.value.gender,
        searchEmp.value.begin,
        searchEmp.value.end,
        page.value,
        pageSize.value,
    )
    empTableData.value = res.data.rows
    console.log(res.data.total)
    total.value = res.data.total
}

// 每页数量改变
const handleSizeChange = (val)=>{
  pageSize.value = val
  searchPage()
}
// 页数查询
const handleCurrentChange = (val)=>{
  page.value = val
  searchPage()
}

const query = ()=>{
  searchPage()
}

const clear = ()=>{
  searchEmp.value = {
    name: '',
    gender: '',
    date: [],
    begin: '',
    end: ''
  }
  searchPage()
}

// 删除员工
const handleDel = (id)=>{
  const ids = [id]
  delDataByIds(ids)
}

const delEmps = ref([])
// 批量删除
const handleSelectionChange = (val)=>{
  val.forEach(element => {
    delEmps.value.push(element.id)
  });
}

const deleteEmps = () => {
  delDataByIds(delEmps.value)
}


// 根据id数组批量删除数据 
const delDataByIds = (ids) => {
  ElMessageBox.confirm(
    '是否确定删除该员工？',
    '| 删除员工',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async() => {
    const res = await deleteEmpById(ids)
    if (res.code) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      searchPage()
    } else {
      ElMessage.error(res.msg)
    }
    
  })
}

// dialog窗体
const dialog_title = ref('')

// 新增员工
const dialogVisible = ref(false)
const empsList = ref([])
// 员工经验
const empexrp = ref({
  company: "",
  job: "",
  begin: "",
  end: "" 
})
// 员工信息
const emp = ref({
  image: "https://web-framework.oss-cn-hangzhou.aliyuncs.com/2022-09-03-07-37-38222.jpg",
  username: "",
  name: "",
  gender: "",
  job: "",
  entryDate: "",
  deptId: "",
  phone: "",
  salary: 0,
  exprList: [empexrp.value]
})

// 清空数据
const clearDiglog = ()=>{
  empexrp.value = {
    company: "",
    job: "",
    begin: "",
    end: "" 
  }
  emp.value = {
    image: "https://web-framework.oss-cn-hangzhou.aliyuncs.com/2022-09-03-07-37-38222.jpg",
    username: "",
    name: "",
    gender: "",
    job: "",
    entryDate: "",
    deptId: "",
    phone: "",
    salary: 0,
    exprList: [empexrp.value]
  }
}

const addEmpDialog = async()=>{
  clearDiglog()
  dialogVisible.value = true
  const res = await queryAllapi()
  empsList.value =res.data
  dialog_title.value = '添加员工'
}
const addWorkExperience = () => {
  emp.value.exprList.push(ref({
  company: "",
  job: "",
  begin: "",
  end: "" 
}))
}
const removeWorkExperience = (index) => {
  emp.value.exprList.splice(index, 1)
}

const submitForm = async () => {
  let res = null;
  if (dialog_title.value === '添加员工') {
    res = await addEmpApi(emp.value)
  } else {
    res = await updateApi(emp.value)
  }
  
  if (res.code) {
    ElMessage({
      type: 'success',
      message: '成功'
    })
    searchPage()
  } else {
    ElMessage.error(res.msg)
  }
  dialogVisible.value = false
}
// 编辑数据
const handleEdit = async(id) => {
  clearDiglog()
  dialogVisible.value = true
  dialog_title.value = '编辑员工'
  const res = await queryAllapi()
  empsList.value =res.data

  // 查询数据
  const empRes = await queryByIdApi(id)
  emp.value = empRes.data
}
</script>

<style scope>

</style>